package com.why.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.io.InputStream;

public class FtpUtil {
    //ip地址
    private static final String FTP_ADDRESS="47.104.137.246";
    //端口号
    private static final int FTP_PORT= 21;

    //ftp用户名
    private static final String FTP_USERNAME="hy";
    //ftp密码
    private static final String FTP_PASSWORD="hy";

    private static final String FTP_BASEPATH="/home/hy/files";
    //文件上传                                   //文件名       io输入流
    public static boolean uploadFile(String fileName, InputStream input){
        boolean success=false;
        //new有个客户端
        FTPClient ftp=new FTPClient();
        try {
            int reply;

            ftp.connect(FTP_ADDRESS,FTP_PORT);
            ftp.login(FTP_USERNAME,FTP_PASSWORD);
            reply=ftp.getReplyCode();
            //如果没有连上，那么就自动断开
            if (!FTPReply.isPositiveCompletion(reply)){
                ftp.disconnect();
                return false;
            }
            ftp.setControlEncoding("UTF-8");
            //设置文件类型                二进制
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            //创建文件夹
            // ftp.makeDirectory(FTP_BASEPATH);
            //改变目录
            ftp.changeWorkingDirectory(FTP_BASEPATH);
            ftp.enterLocalActiveMode();
            //传文件
            ftp.storeFile(fileName, input);
            //输入流关闭
            input.close();
            //ftp注销
            ftp.logout();
            success=true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()){
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
}
